#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>
#include <QFileInfo>
#include <QMdiSubWindow>
#include <QMessageBox>
#include <QSettings>

MainWindow::MainWindow(QWidget* parent)
	: QMainWindow(parent)
	, ui(new Ui::MainWindow)
{
    ui->setupUi(this);
	readSettings();
	actionSeparator = new QAction(this);
	actionSeparator->setSeparator(true);
	updateMenus();

	connect(ui->mdiArea, &QMdiArea::subWindowActivated, this, &MainWindow::updateMenus);

	windowManager = new QSignalMapper(this);
	//参数需要转换，加了中间处理 static_cast无效？？
	connect(windowManager, static_cast<void (QSignalMapper::*)(QWidget*)>(&QSignalMapper::mapped),
		this, &MainWindow::mapped);

	updateWindowMenus();

	connect(ui->menuWindow, &QMenu::aboutToShow, this, &MainWindow::updateWindowMenus);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionNew_triggered()
{
	MdiChild* child = createMdiChild();
    child->newFile();
	child->show();
}

void MainWindow::updateMenus()
{
	bool hasMdiChild = (activeMdiChild() != nullptr);
	ui->actionClose->setEnabled(hasMdiChild);
	ui->actionCloseAll->setEnabled(hasMdiChild);
	ui->actionTile->setEnabled(hasMdiChild);
	ui->actionCascade->setEnabled(hasMdiChild);
	ui->actionNext->setEnabled(hasMdiChild);
	ui->actionPrevious->setEnabled(hasMdiChild);
	ui->actionPaste->setEnabled(hasMdiChild);
	ui->actionSave->setEnabled(hasMdiChild);
	ui->actionSaveAs->setEnabled(hasMdiChild);
	actionSeparator->setEnabled(hasMdiChild);

	bool hasSelection = (activeMdiChild() && activeMdiChild()->textCursor().hasSelection());

	ui->actionCopy->setEnabled(hasSelection);
	ui->actionCut->setEnabled(hasSelection);

	ui->actionUndo->setEnabled(activeMdiChild() && activeMdiChild()->document()->isUndoAvailable());
	ui->actionRedo->setEnabled(activeMdiChild() && activeMdiChild()->document()->isRedoAvailable());
}

MdiChild* MainWindow::createMdiChild()
{
	MdiChild* child = new MdiChild;
	ui->mdiArea->addSubWindow(child);

	connect(child, &MdiChild::copyAvailable, ui->actionCopy, &QAction::setEnabled);
	connect(child, &MdiChild::copyAvailable, ui->actionCut, &QAction::setEnabled);

	connect(child->document(), &QTextDocument::undoAvailable, ui->actionUndo, &QAction::setEnabled);
	connect(child->document(), &QTextDocument::redoAvailable, ui->actionRedo, &QAction::setEnabled);

	return child;
}

void MainWindow::mapped(QWidget* wid)
{
	ui->mdiArea->setActiveSubWindow(static_cast<QMdiSubWindow*>(wid));
}

MdiChild* MainWindow::activeMdiChild()
{
	if (QMdiSubWindow* localactivesubwindow = ui->mdiArea->activeSubWindow())
		return qobject_cast<MdiChild*>(localactivesubwindow->widget());
	return nullptr;
}

QMdiSubWindow* MainWindow::findMdiChild(QString& fileName)
{
	QString localCanonicalFilePath = QFileInfo(fileName).canonicalFilePath();
	for (auto child : ui->mdiArea->subWindowList()) {
		if (qobject_cast<MdiChild*>(child->widget())->currentFile() == localCanonicalFilePath)
			return child;
	}
	return nullptr;
}

void MainWindow::updateWindowMenus()
{
	ui->menuWindow->clear();

	ui->menuWindow->addAction(ui->actionClose);
	ui->menuWindow->addAction(ui->actionCloseAll);
	ui->menuWindow->addSeparator();
	ui->menuWindow->addAction(ui->actionTile);
	ui->menuWindow->addAction(ui->actionCascade);
	ui->menuWindow->addSeparator();
	ui->menuWindow->addAction(ui->actionNext);
	ui->menuWindow->addAction(ui->actionPrevious);
	ui->menuWindow->addSeparator();
	ui->menuWindow->addAction(actionSeparator);

	auto windowList = ui->mdiArea->subWindowList();
	actionSeparator->setVisible(!windowList.isEmpty());

	for (auto action : windowList) {
		MdiChild* child = static_cast<MdiChild*>(action->widget());
		QString title = child->userFriendlyCurrentFile();
		QAction* localAddAction = ui->menuWindow->addAction(title);
		localAddAction->setCheckable(true);
		localAddAction->setChecked(child == activeMdiChild());
		//Qt新语法如何完成？
		connect(localAddAction, SIGNAL(triggered()), windowManager, SLOT(map()));
		//		connect(localAddAction,&QAction::triggered,windowManager,&QSignalMapper::map);

		windowManager->setMapping(localAddAction, windowList.at(windowList.indexOf(action)));
	}
}

void MainWindow::readSettings()
{
	QSettings setting("cn.com.wanywhn","myMdi");
	QPoint p=setting.value("pos",QPoint(200,200)).toPoint();
	QSize size=setting.value("size",QSize(500,200)).toSize();
	move(p);
	this->resize(size);
}

void MainWindow::saveSettings()
{
	QSettings setting("cn.com.wanywhn","myMdi");
	setting.setValue("pos",pos());
	setting.setValue("size",size());
}

void MainWindow::on_actionOpen_triggered()
{
	QString openFileName = QFileDialog::getOpenFileName(this);
	if (openFileName.isEmpty())
		return;
	QMdiSubWindow* existing = findMdiChild(openFileName);
	if (existing)
		ui->mdiArea->setActiveSubWindow(existing);
	else {
		MdiChild* child = createMdiChild();
		if (child->loadFile(openFileName)) {
			ui->statusBar->showMessage("Open Success");
			child->show();
		} else {
			child->close();
		}
	}
	return;
}

void MainWindow::on_actionSave_triggered()
{
	if (activeMdiChild() && activeMdiChild()->save())
		ui->statusBar->showMessage(tr("保存成功"));
}

void MainWindow::on_actionSaveAs_triggered()
{
	if (activeMdiChild() && activeMdiChild()->saveAs())
		ui->statusBar->showMessage("另存为成功");
}

void MainWindow::on_actionExit_triggered()
{
	qApp->closeAllWindows();
}

void MainWindow::on_actionUndo_triggered()
{
	if (activeMdiChild())
		//		activeMdiChild()->document()->undo();
		activeMdiChild()->undo();
}

void MainWindow::on_actionRedo_triggered()
{
	if (activeMdiChild())
		activeMdiChild()->redo();
}

void MainWindow::on_actionCut_triggered()
{
	if (activeMdiChild())
		activeMdiChild()->cut();
}

void MainWindow::on_actionCopy_triggered()
{

	if (activeMdiChild())
		activeMdiChild()->copy();
}

void MainWindow::on_actionPaste_triggered()
{

	if (activeMdiChild())
		activeMdiChild()->paste();
}

void MainWindow::on_actionClose_triggered()
{
	ui->mdiArea->closeActiveSubWindow();
}

void MainWindow::on_actionCloseAll_triggered()
{
	for (auto window : ui->mdiArea->subWindowList()) {
		window->close();
	}
}

void MainWindow::on_actionTile_triggered()
{
	ui->mdiArea->tileSubWindows();
}

void MainWindow::on_actionCascade_triggered()
{
	ui->mdiArea->cascadeSubWindows();
}

void MainWindow::on_actionNext_triggered()
{
	ui->mdiArea->activateNextSubWindow();
}

void MainWindow::on_actionPrevious_triggered()
{
	ui->mdiArea->activatePreviousSubWindow();
}

void MainWindow::on_actionAboutQt_triggered()
{
	QMessageBox::aboutQt(this);
}

void MainWindow::on_actionAbout_triggered()
{
	QMessageBox::about(this, "关于", "练手");
}

void MainWindow::closeEvent(QCloseEvent* event)
{
	ui->mdiArea->closeAllSubWindows();
	if (ui->mdiArea->currentSubWindow()) {
		event->ignore();
	} else {
		saveSettings();
		event->accept();
	}
}
